package com.common.web.interceptor;

import com.common.annotation.PreAuthorize;
import com.common.exception.BizException;
import com.common.rpc.IPassportRPC;
import com.common.util.RPCResult;
import com.common.util.StringUtils;
import com.common.util.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public abstract class RoleResourceInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private HttpServletRequest request;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            if (method != null && method.getMethodAnnotation(PreAuthorize.class) != null) {
                PreAuthorize methodAnnotation = (PreAuthorize) method.getMethodAnnotation(PreAuthorize.class);
                if (methodAnnotation == null) {
                    return true;
                }
                RPCResult<UserDto> result = check(getToken());
                if(!result.getSuccess()){
                    throw new BizException("token.error");
                }
                UserDto user = result.getData();
                request.setAttribute("user",user);
                String pin = user.getPin();
                String resource = methodAnnotation.value();
                if (StringUtils.isBlank(resource) && StringUtils.isNotBlank(pin)) {
                    return true;
                }
                if (user.getAdmin()) {
                    return true;
                }
                long count = user.getPermissions().stream().filter((item) -> item.equals(methodAnnotation.value())).count();
                if (count > 0) {
                    return true;
                }
                throw new BizException("no.right");
            }

        }
        return true;
    }

    protected String getToken() {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (cookie.getName().equals("token")) {
                        return cookie.getValue();
                    }
                }
            }
            throw new BizException("token.error", "登录失效");
        }
        return token;
    }

    protected abstract RPCResult<UserDto> check(String token);
}
